<template>
	<div class="admin-list">
		<list-title :data="header" @changeVisible="changeVisible"></list-title>
		<list-table :list="adminList" :tableLoading="tableLoading" :footer="false">
			<template v-slot:data>
				<el-table-column prop="username" label="用户名"></el-table-column>
				<el-table-column prop="role_id" label="角色"></el-table-column>
				<el-table-column prop="lastloginip" label="最后登录IP"></el-table-column>
				<el-table-column prop="lastlogin_time" label="最后登录时间"></el-table-column>
				<el-table-column prop="creater" label="创建者"></el-table-column>
				<el-table-column label="锁定/启用">
					<template slot-scope="scope">
						<el-switch v-model="scope.row.state" @change="changeState(scope.$index, scope.row)"></el-switch>
					</template>
				</el-table-column>
				<el-table-column prop="logintimes" label="登录次数"></el-table-column>
				<el-table-column prop="add_time" label="注册时间"></el-table-column>
				<el-table-column label="操作" width="100">
					<template slot-scope="scope">
						<el-button type='text' size="mini" @click="handleEdit(scope.$index, scope.row)" v-if="auth.editor">编辑</el-button>
						<el-popover
						placement="top"
						width="160"
						v-model="delTip[scope.$index+1]" v-if="auth.delete">
							<p class="del-tip"><span class="el-icon-question"></span>确定删除吗？</p>
							<div style="text-align: right; margin: 0">
								<el-button size="mini" type="text" @click="delTip.splice(scope.$index+1, 1, false)">取消</el-button>
								<el-button type="primary" size="mini" @click="handleDelete(scope.$index, scope.row)">确定</el-button>
							</div>
							<el-button type="text" slot="reference" :disabled='submitLock[scope.$index+1]'>
								删除 <span class="el-icon-loading" v-if='submitLock[scope.$index+1]'></span>
							</el-button>
						</el-popover>
					</template>
				</el-table-column>
			</template>
		</list-table>
		<!-- 添加 开始 -->
		<el-dialog :title="dialogTitle" :visible.sync="header.dialogs[0].visible" width="480px">
			<el-form :model="adminForm" :rules="rules" ref="adminForm" label-width="100px">
				<el-form-item label="账户名" prop="data.username" style="width: 398px;">
					<el-input v-model="adminForm.data.username" placeholder="账户名" :disabled="adminForm.data.edit"></el-input>
				</el-form-item>
				<el-form-item label="管理员密码" prop="data.password" style="width: 398px;" required  v-if="!adminForm.data.edit">
					<el-input type="password" v-model="adminForm.data.password" placeholder="管理员密码"></el-input>
				</el-form-item>
				<el-form-item label="确认密码" prop="data.passwordConfirm" style="width: 398px;" required  v-if="!adminForm.data.edit">
					<el-input type="password" v-model="adminForm.data.passwordConfirm" placeholder="确认密码"></el-input>
				</el-form-item>
				<el-form-item label="选择角色" prop="data.role_id">
					<el-select v-model="defaultRole" placeholder="请选择角色">
						<el-option v-for="(item, index) in adminRoleList" :key="index" :label="item.rolename" :value="parseInt(item.role_id)"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="允许登录日期" prop="data.allowlogindate" style="width: 398px;">
					<el-checkbox-group v-model="adminForm.data.allowlogindate">
						<el-checkbox label="1" name="type">星期一</el-checkbox>
						<el-checkbox label="2" name="type">星期二</el-checkbox>
						<el-checkbox label="3" name="type">星期三</el-checkbox>
						<el-checkbox label="4" name="type">星期四</el-checkbox>
						<el-checkbox label="5" name="type">星期五</el-checkbox>
						<el-checkbox label="6" name="type">星期六</el-checkbox>
						<el-checkbox label="7" name="type">星期天</el-checkbox>
					</el-checkbox-group>
				</el-form-item>
				<el-form-item label="状态" prop="data.state">
					<el-tooltip :content="'当前状态: ' + (adminForm.data.state===true?'启用':'锁定')" placement="top">
						<el-switch v-model="adminForm.data.state"></el-switch>
					</el-tooltip>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="header.dialogs[0].visible = false">取 消</el-button>
				<el-button type="primary" @click="submitForm('adminForm')" :disabled='adminForm.submitLock'>
					确 定 <span class="el-icon-loading" v-if='adminForm.submitLock'></span>
				</el-button>
			</div>
		</el-dialog>
		<!-- 添加 结束 -->
	</div>
</template>

<script>
import ListTitle from "pc/common/Title"
import ListTable from "pc/common/ListTable"
import {changeToBool, judgeAuth} from "static/js/common.js"
import {mapGetters} from 'vuex'

export default {
	inject: ['reload'],
	data() {
		var validatePass = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('请输入密码'));
			} else {
				if (this.adminForm.data.password !== '') {
					this.$refs.adminForm.validateField('password');
				}
				if (this.adminForm.data.password.length < 6) {
					callback(new Error('密码不能少于6位'));
				}
				callback();
			}
		};
		var validatePass2 = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('请再次输入密码'));
			} else if (value !== this.adminForm.data.password) {
				callback(new Error('两次输入密码不一致!'));
			} else {
				callback();
			}
		};
		return {
			/*头部数据*/
			header: {
				title: '管理员列表',
				reload: true,
				dialogs: [
					{
						title: '添加管理员',
						type: 'primary',
						visible: false,
						auth: false,
					}
				]
			},
			auth: {
				editor: false,//编辑
				delete: false,//删除
			},
			dialogTitle: '添加管理员',//dialog标题
			/*列表数据*/
			adminList: [
				// {
				// 	admin_id: 1,
				// 	username: 'admin',
				// 	role_id: '营业员',
				// 	lastloginip: '127.0.0.1',
				// 	lastlogin_time: '2019-08-28',
				// 	creater: 'system',
				// 	state: '1',
				// 	logintimes: 88,
				// 	add_time: '2018-01-16',
				// },
			],
			/*角色列表数据*/
			adminRoleList: [
				// {
				// 	role_id: 1,
				// 	rolename: '仓管员',
				// },
			],
			tableLoading: true,
			delTip: [],//刪除提示
			submitLock: [],
			/*添加表单数据*/
			adminForm: {
				submitLock: false,
				edit: false,//true 说明是编辑，false说明是添加 主要为了有些dom不显示
				data: {
					id: 0,
					username: '',
					password: '',
					passwordConfirm: '',
					role_id: '',
					allowlogindate: ['1', '2', '3', '4', '5'],
					state: true,
				}
			},
			rules: {
				data: {
					username: [
						{ required: true, message: '请输入账户名', trigger: 'blur' },
						{ min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' }
					],
					password: [
						{ validator: validatePass, trigger: 'blur' }
					],
					passwordConfirm: [
						{ validator: validatePass2, trigger: 'blur' }
					]
				}
			}
		};
	},
	components: {
		ListTitle,
		ListTable
	},
	created: function() {
		/*取出comid，如果没有则跳转到 企业列表 */
		/*注释原因：登录后 后台已经知道用户的comid等相关信息了*/
		// this.adminForm.data.comid = this.comid = JSON.parse(this.$localstorage.get('uinfo')).comid
		/*获取列表数据*/
		this.getAdminList()
		/*权限判断显示*/
		this.header.dialogs[0].auth = (judgeAuth('addAdmin', this.allMenuList) == undefined)?false:true
		this.auth.editor = (judgeAuth('modifyAdmin', this.allMenuList) == undefined)?false:true
		this.auth.delete = (judgeAuth('deleteAdmin', this.allMenuList) == undefined)?false:true
	},
	methods: {
		/*获取用户数据*/
		getAdminList: function(){
			if(this.$api.adminList != undefined){			
				this.$get(this.$api.adminList).then(res => {
					// console.log(res);
					if(res.data.code === 0){
						if(res.data.data != undefined){
							this.adminList = []
							Object.keys(res.data.data).forEach((k) => {
								this.adminList.push ({
									admin_id: res.data.data[k].admin_id,
									username: res.data.data[k].username,
									role_id: (res.data.data[k].adminRole != null)?res.data.data[k].adminRole.rolename:'-',
									lastloginip: (res.data.data[k].lastloginip != 0)?res.data.data[k].lastloginip:'-',
									lastlogin_time: (res.data.data[k].lastlogin_time != '1000-01-01 00:00:00')?res.data.data[k].lastlogin_time:'-',
									creater: res.data.data[k].creater,
									state: changeToBool(res.data.data[k].state),
									logintimes: res.data.data[k].logintimes,
									add_time: res.data.data[k].add_time,
								});
							})
						}
						this.tableLoading = false
					}
				})
				.catch(err => {})
				.finally(() => {}) 
			}
		},
		/*获取列表数据*/
		getRoleList: function(){
			if(this.$api.adminRoleList != undefined){
				this.$get(this.$api.adminRoleList, {
					'display': 2
				}).then(res => {
					if(res.data.code === 0){
						if(res.data.data != undefined){
							this.adminRoleList = []
							Object.keys(res.data.data).forEach((k) => {
								this.adminRoleList.push ({
									role_id: res.data.data[k].role_id,
									rolename: res.data.data[k].rolename,
								});
							})
						}
						this.tableLoading = false
					}
				})
				.catch(err => {})
				.finally(() => {}) 
			}
		},
		/*编辑 打开编辑窗口，获取数据*/
		handleEdit(index, row) {
			// console.log(row)
			if(this.$api.modifyAdmin != undefined){
				this.adminForm.submitLock = true;
				/*取出需要修改的数据*/
				this.dialogTitle = '编辑管理员'
				this.header.dialogs[0].visible = true//显示修改的窗口
				this.$nextTick(() => {
					this.$refs.adminForm.resetFields()//清空表单
				})
				this.adminForm.data.edit = true//指明是编辑

				/*如果角色列表没有数据，则取出来*/
				if(!this.adminRoleList.length){
					this.getRoleList();
				}

				this.$get(this.$api.modifyAdmin, {
					'id': row.admin_id
				}).then(res => {
					if(res.data.code == 0){
						// console.log(res.data.data)
						this.adminForm.data.id = res.data.data.admin_id
						this.adminForm.data.username = res.data.data.username
						this.adminForm.data.role_id = parseInt(res.data.data.role_id)
						this.adminForm.data.allowlogindate = res.data.data.allowlogindate.split(',')
						this.adminForm.data.state = changeToBool(res.data.data.state)
					}else{
						this.$message({
							showClose: true,
							message: res.data.info,
							type: 'error'
						});
					}
					this.adminForm.submitLock = false;
				})
				.catch(err => {})
				.finally(() => {}) 
			}
		},
		/*dialog切换 方便子组件调用*/
		changeVisible: function(index){
			/*因为子组件调用的都是添加的行为，所以需要把id置为0(方便判断是添加还是修改)，title改为'添加管理员'*/
			this.dialogTitle = '添加管理员'
			this.adminForm.data.id = 0

			this.header.dialogs[index].visible = !this.header.dialogs[index].visible
			this.adminForm.data.edit = false

			this.$nextTick(() => {
				this.$refs.adminForm.resetFields()//清空表单
			})

			/*如果角色列表没有数据，则取出来*/
			if(!this.adminRoleList.length){
				this.getRoleList();
			}
		},
		/*提交添加、修改表单*/
		submitForm(formName) {
			if(!this.adminForm.submitLock){
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.adminForm.submitLock = true;
						/*添加、修改分类*/
						// console.log(this.adminForm.data)
						let apiUrl = this.$api.addAdmin//默认是添加
						if(this.adminForm.data.id > 0){//修改
							apiUrl = this.$api.modifyAdmin
						}
						if(apiUrl != undefined){
							this.$post(apiUrl, {
								Admin: this.adminForm.data
							}).then(res => {
								// console.log(res);
								/*成功*/
								if(res.data.code == 0){
									this.getAdminList()
									this.$message({
										showClose: true,
										message: res.data.info,
										type: 'success'
									});
									// if(this.adminForm.data.id > 0){//修改的话，关闭dialog
										this.header.dialogs[0].visible = false
									// }
									this.$refs[formName].resetFields();
								}else{
									this.$message({
										showClose: true,
										message: res.data.info,
										type: 'error'
									});
								}
								this.adminForm.submitLock = false;
							});
						}
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			}
		},
		/*列表中直接修改 更改状态*/
		changeState(index, row){
			if(this.$api.modifyAdmin != undefined){
				/*请求后台*/
				this.$post(this.$api.modifyAdmin, {
					'Admin': {
						'id': row.admin_id,
						'state': row.state,
					}
				}).then(res => {
					if(res.data.code == 0){
						this.$message({
							showClose: true,
							message: res.data.info,
							type: 'success'
						});
					}else{
						this.$message({
							showClose: true,
							message: res.data.info,
							type: 'error'
						});
					}
				})
				.catch(err => {})
				.finally(() => {})
			}else{
				this.$message({
					showClose: true,
					message: '您没有更改状态的权限',
					type: 'error'
				});
			}
		},
		/*删除*/
		handleDelete(index, row) {
			if(this.$api.deleteAdmin != undefined){
				if(!this.submitLock[index+1]){
					this.submitLock[index+1] = true//锁住当前的 删除按钮
					this.delTip.splice(index+1, 1, false)//提示消失
					/*请求后台删除*/
					this.$post(this.$api.deleteAdmin, {
						'id': row.admin_id,
					}).then(res => {
						if(res.data.code == 0){
							this.$message({
								showClose: true,
								message: res.data.info,
								type: 'success'
							});
							this.adminList.splice(index, 1);//删除当前行
						}else{
							this.$message({
								showClose: true,
								message: res.data.info,
								type: 'error'
							});
						}
						this.submitLock[index+1] = false//释放当前的 删除按钮
					})
					.catch(err => {})
					.finally(() => {}) 
				}
			}
		},
	},
	computed: {
		...mapGetters([
			'allMenuList'
		]),
		/*角色的默认值，是否在列表中存在，如果不存在，则不显示，避免显示数字的尴尬*/
		defaultRole: {
			get: function(){
				for(let i=0; i<this.adminRoleList.length; i++){
					if(this.adminForm.data.role_id == this.adminRoleList[i].role_id){
						return this.adminForm.data.role_id
					}
				}
				return ''
			},
			set: function(val){
				this.adminForm.data.role_id = val
			}
		}
	}
};
</script>

<style lang="stylus" scoped>
</style>